using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using FishNet.Object;
using UnityEngine.UI;
using FishNet.Managing.Timing;
using FishNet.Component.ColliderRollback;

public class PlayerController : NetworkBehaviour
{
    private bool IsPlayer1;
    private Text _playerText;
    private Text _messageText;

    public float Speed = 2;

    // Start is called before the first frame update
    private void Start()
    {
        if (transform.position.z < 0)
        {
            IsPlayer1 = true;
        }

        if (IsPlayer1 == false)
        {
            transform.position = new Vector3(10, transform.position.y, transform.position.z);
        }

        GameObject go = GameObject.Find("PlayerText");
        _playerText = go.GetComponent<Text>();

        GameObject go_message = GameObject.Find("MessageText");
        _messageText = go_message.GetComponent<Text>();
    }

    // Update is called once per frame
    private void Update()
    {
        if (IsOwner)
        {
            if (IsPlayer1 == true)
            {
                _playerText.text = "Player 1";

                if (Input.GetKeyDown(KeyCode.Space))
                {
                    Fire();
                }
            }
            else
            {
                _playerText.text = "Player 2";

                transform.Translate(Vector3.left * Speed * Time.deltaTime);

                if (transform.position.x < -10)
                {
                    transform.position = new Vector3(10, transform.position.y, transform.position.z);
                }
            }
        }
    }

    [Client]
    private void Fire()
    {
        //Use LastPacketTick to get the best tick alignment.
        PreciseTick pt = base.TimeManager.GetPreciseTick(base.TimeManager.LastPacketTick);

        _messageText.text += "ClientFire Time=" + System.DateTime.Now + "  Tick=" + pt.Tick + "\n";

        //Call fire on the server.
        ServerFire(pt);
    }

    [ServerRpc]
    private void ServerFire(PreciseTick pt)
    {
        //Rollback using the precise tick sent in.
        base.RollbackManager.Rollback(pt, RollbackManager.PhysicsType.ThreeDimensional, base.IsOwner);
        //Perform your raycast normally.
        RaycastHit hit;
        if (Physics.Raycast(transform.position, transform.forward, out hit))
        {
            if (hit.collider.tag == "Player")
            {
                _messageText.text += "ServerFire Time=" + System.DateTime.Now + "  Tick=" + pt.Tick + "\n";
            }
        }
        //Return the colliders to their proper positions.
        base.RollbackManager.Return();
    }
}